<template>
	<div class="aq-upload-img">
		<!-- 按钮样式 -->
		<el-upload
			v-if="props.uploadType === 'button'"
			:file-list="fileList"
			:headers="uploadHeader"
			:action="props.uploadAction"
			:multiple="props.multiple"
			:before-remove="beforeRemove"
			:on-remove="handleRemove"
			:limit="props.limit"
			:accept="accept"
			:on-success="handleSuccess"
			:on-error="handleError"
			:before-upload="beforeUpload"
			:on-exceed="handleExceed"
			:on-progress="handleProgress"
		>
			<el-button plain>
				<el-icon style="margin-right: 5px">
					<Upload />
				</el-icon>
				上传{{ props.buttonName }}
			</el-button>
			<template #tip>
				<div class="el-upload__tip">
					格式要求：{{ accept }}，数量限制{{ props.limit }}个，每个{{ props.buttonName }}小于{{ props.uploadSize }}M
				</div>
			</template>
		</el-upload>
		<!-- 框样式 -->
		<el-upload
			v-if="props.uploadType === 'box'"
			list-type="picture-card"
			:show-file-list="false"
			:file-list="props.fileList"
			:headers="uploadHeader"
			:action="props.uploadAction"
			:multiple="props.multiple"
			:before-remove="beforeRemove"
			:on-remove="handleRemove"
			:limit="props.limit"
			:accept="accept"
			:on-success="handleSuccess"
			:on-error="handleError"
			:before-upload="beforeUpload"
			:on-exceed="handleExceed"
			:on-progress="handleProgress"
		>
			<el-icon><Plus /></el-icon>
		</el-upload>
	</div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();
const props = defineProps({
	uploadType: {
		//上传类型：button-按钮型，box-框型
		type: String,
		default: 'button'
	},
	limit: {
		type: Number,
		default: 2
	},
	multiple: {
		type: Boolean,
		default: false
	},
	token: {
		type: String,
		default: ''
	},
	uploadAction: {
		type: String,
		default: ''
	},
	acceptList: {
		//文件类型数组 ['.jpg', '.png']，注意：上传类型为box模式下只能配置上传图片的格式，其它比如.rar不生效
		type: Array,
		default: []
	},
	buttonName: {
		//按钮的名字
		type: String,
		default: '图片'
	},
	uploadSize: {
		//单个上传文件的大小MB
		type: Number,
		default: 10
	}
});

let accept = ref(props.acceptList.join(', '));
const emits = defineEmits(['update:imgValue']);
const uploadHeader = {
	Authorization: props.token
};
let fileList = ref([]);
const beforeRemove = (file, fileLists) => {
	if (file && file.status === 'success') {
		return ElMessageBox.confirm(`是否要删除该${props.buttonName}`, '温馨提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => true)
			.catch(() => false);
	} else {
		let index = 0;
		for (const i in fileLists) {
			if (fileLists[i] == file) {
				index = i;
				break;
			}
		}
		//移出当前文件对象
		fileLists.splice(index, 1);
		return false;
	}
};
const handleRemove = (file) => {
	// console.log('删除', file);
	fileList.value = fileList.value.filter((item) => item.url != file.url);
};
let loading = null;
const beforeUpload = (rawFile) => {
	// 所有文件类型
	let fileType = {
		'.jpg': 'image/jpeg',
		'.jpeg': 'image/jpeg',
		'.png': 'image/png',
		'.gif': 'image/gif',
		'.bmp': 'image/bmp',
		'.svg': 'image/svg+xml',
		'.zip': 'application/x-zip-compressed',
		'.rar': 'application/x-rar-compressed',
		'.7z': 'application/x-7z-compressed',
		'.gzip': 'application/gzip',
		'.tar': 'application/x-tar',
		'.pdf': 'application/pdf',
		'.doc': 'application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document',
		'.docx': 'application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document',
		'.xls': 'application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
		'.xlsx': 'application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
		'.ppt': 'application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation',
		'.pptx': 'application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation'
	};
	let flag = false;
	for (let item of props.acceptList) {
		if (rawFile.type == fileType[item]) {
			flag = true;
			break;
		}
	}
	if (props.acceptList.length > 0 && !flag) {
		ElMessage.error(`只能上传${accept.value}格式${props.buttonName}`);
		return false;
	} else if (rawFile.size / 1024 / 1024 > props.uploadSize) {
		ElMessage.error(`上传${props.buttonName}大小不能超过 ${props.uploadSize}MB!`);
		return false;
	} else {
		return true;
	}
};
const handleProgress = () => {
	loading = ElLoading.service({
		text: '上传中...',
		spinner: 'el-icon-loading'
	});
};
const handleSuccess = (res, file, fileLists) => {
	loading & loading.close();
	if (res.code == 200) {
		if (fileList.value) {
			fileList.value.push({
				url: res.data.absolutePath,
				name: file.name
			});
		} else {
			fileList.value = [
				{
					url: res.data.absolutePath,
					name: file.name
				}
			];
		}
		ElMessage({
			message: `${props.buttonName}上传成功!`,
			type: 'success'
		});
		emits('update:imgValue', fileList);
	} else {
		let index = 0;
		for (const i in fileLists) {
			if (fileLists[i] == file) {
				index = i;
				break;
			}
		}
		//移出当前文件对象
		fileLists.splice(index, 1);
		ElMessageBox.confirm(res.msg, `${props.buttonName}上传失败`, {
			confirmButtonText: '确定',
			showCancelButton: false,
			type: 'warning'
		}).then(() => {});
	}
};
const handleError = (file) => {
	loading & loading.close();
	ElMessage.error('上传失败，请重新上传!');
};
const handleExceed = (files, uploadFiles) => {
	ElMessage.error(`最多只能上传${props.limit}个${props.buttonName}!`);
};
</script>

<style lang="scss">
.aq-upload-img {
}
</style>
